﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FYP14
{
    public partial class AddAppointment : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetAllPatients();
                GetAllSchedules();
                if (Request.QueryString["ID"] != null)
                {
                    SetValues(Convert.ToInt32(Request.QueryString["ID"]));
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Appointment oAppointment = new Appointment();
            oAppointment.Patient_ID = Convert.ToInt32(ddlPatient.SelectedValue);
            oAppointment.Schedule_ID = Convert.ToInt32(ddlSchedule.SelectedValue);
            oAppointment.appointment_type = txtAppointmentType.Text;
            oAppointment.appointment_date = Convert.ToDateTime(((TextBox)(dtcdate.FindControl("TextBox1"))).Text);

            if (Request.QueryString["ID"] != null)
            {
                oAppointment.Appointment_ID = Convert.ToInt32(Request.QueryString["ID"]);
                BAL.UpdateAppointment(oAppointment);
            }
            else
            {
                BAL.SaveAppointment(oAppointment);
            }

            Response.Redirect("ViewAppoinments.aspx");
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("ViewAppoinments.aspx");
        }

        private void SetValues(Int32 ID)
        {
            DataTable dt = BAL.GetAppointment(ID);
            if (dt.Rows.Count > 0)
            {
                ddlPatient.Items[ddlPatient.Items.IndexOf(ddlPatient.Items.FindByValue(dt.Rows[0]["patient_id"].ToString()))].Selected = true;
                ddlSchedule.Items[ddlSchedule.Items.IndexOf(ddlSchedule.Items.FindByValue(dt.Rows[0]["Schedule_id"].ToString()))].Selected = true;
                txtAppointmentType.Text = dt.Rows[0]["Appointment_type"].ToString();
                ((TextBox)(dtcdate.FindControl("TextBox1"))).Text = dt.Rows[0]["Appointment_Date"].ToString();
            }
        }

        private void GetAllPatients()
        {
            DataTable dt = BAL.GetAllPatients();
            ddlPatient.DataTextField = "name";
            ddlPatient.DataValueField = "patient_id";
            ddlPatient.DataSource = dt;
            ddlPatient.DataBind();
        }

        private void GetAllSchedules()
        {
            DataTable dt = BAL.GetAllSchedules();
            ddlSchedule.DataTextField = "Schedule_name";
            ddlSchedule.DataValueField = "Schedule_id";
            ddlSchedule.DataSource = dt;
            ddlSchedule.DataBind();
        }
    }
}